package com.gameObjects;

import com.badlogic.androidgames.framework.gl.Animation;
import com.badlogic.androidgames.framework.gl.SpriteBatcher;
import com.badlogic.androidgames.framework.gl.TextureRegion;
import com.badlogic.androidgames.framework.math.Vector2;
import com.baseinfinityrun.Assets;

public class Player extends GameObject
{
	public float animTime;
	private float jumpForce,ground;
	private boolean jumping;
	private Vector2 velocity, accel, jump;
	
	public Player(float x, float y, float w, float h)
	{
		super(x, y, w, h);
		this.tag = "player";
		animation = Assets.player;
		animTime = 0;
		velocity = new Vector2();
		accel = new Vector2();
		jump = new Vector2();
		ground = bounds.height/2 * 0.2f;
	}

	@Override
	public void Update(float deltaTime) 
	{
		bounds.lowerLeft.set(position).sub(bounds.width / 2, bounds.height / 2);
		Walking(deltaTime);
		Jumping(deltaTime);
		Gravity(deltaTime);
	}
	
	private void Jumping(float deltaTime)
	{
		if(jumpForce > 0)
		{
			jump.y = jumpForce * deltaTime;
			jumpForce -= jump.y;
			this.position.add(jump);
			
			if(!jumping)
				jumping = true;
		}
		
		else if(jumpForce < 0)
		{ 
			jumpForce = 0;
		}
	}
	
	private void Gravity(float deltaTime)
	{
		if(this.position.y  > ground + this.bounds.height * 0.5f)
		{
			accel.add(0,-0.3f * deltaTime);
			velocity.set(accel);
			this.position.add(velocity);
		}
		
		else if(this.position.y  < ground + this.bounds.height * 0.5f)
		{
			accel.set(0,0);
			this.position.y  =  ground + this.bounds.height * 0.5f;
			jumpForce = 0;
			jumping = false;
		}
	}
	
	private void Walking(float deltaTime)
	{
		animTime += deltaTime * 2;
		this.position.x += 2 * deltaTime;
	}
	
	public void Jump()
	{
		if(!jumping)
			this.jumpForce = 7;
	}

	@Override
	public void Draw(SpriteBatcher batcher) 
	{
		batcher.beginBatch(Assets.playerAtlas);
        TextureRegion keyFrame = this.animation.getKeyFrame(this.animTime, Animation.ANIMATION_LOOPING);
        batcher.drawSprite(this.position.x, this.position.y, -this.bounds.width, this.bounds.height, keyFrame);
        batcher.endBatch();  
	}
}
